/**
 * 辅助页面计算
 */
import { getStaticState } from "../../state/static-store";
import { CardItemType, ANY_TYPE } from './type';
import { copyJson } from '../../common/tool';
/**
 * 卡片左偏移
 */
export const LEFT_DEVIATION = (11 + 15);
/**
 * 卡片尺寸
 */
export const CARD_SIZE = {
  pool: {
    width: 94,
    height: 94,
  },
  heap: {
    width: 90,
    height: 90
  }
}
/**
 * 卡片点击时间戳
 */
export const timeStemp: ANY_TYPE = {
  cardUpdateTime: 0,
  shimonoseki: 0,
  cardUpdateAnTimer: () => setTimeout(() => {
  }, 20)
}
/**
 * 计算卡片顶部偏差
 */
export const getTopDeviation = () => {
  const ONE_RPX = getStaticState('oneRpx');
  const { screenHeight: SCREEN_HRIGHT, statusBarHeight, safeArea } = getStaticState('systemInfo');
  const TOP_DEVIATION = (((SCREEN_HRIGHT - (statusBarHeight + safeArea.top)) / ONE_RPX - 280) + 10 + 3);
  return TOP_DEVIATION
}
/**
 * 标记卡片池中相同卡片的数量
 */
export const markPoolCard = (poolList) => {
  const hasSortPool = {};
  poolList.forEach(card => {
    if (hasSortPool[card.type] === undefined) {
      hasSortPool[card.type] = {
        count: 1,
        list: [card],
      }
    } else {
      hasSortPool[card.type].count += 1 ;
      hasSortPool[card.type].list.push(card);
    };
  })
  return hasSortPool
}
/**
 * 标记卡片池中可以消除卡片的位置
 */
export const markPoolCardPosition = (hasCount, eliminate) => {

  const destructionPool = {}
  const cachePoolCardList: CardItemType[] = []
  Object.keys(hasCount).forEach(key => {
    if (hasCount[key].count >= eliminate) {
      let count = eliminate;
      while(count > 0) {
        const card = hasCount[key].list.pop();
        destructionPool[card.position] = {isExistence: true}
        count -= 1;
      }
    };
    cachePoolCardList.push(...hasCount[key].list);
  });
  return {
    /**
     * 对需要消失的卡片做标记
     */
    destructionPool,
    /**
     * 卡片池中剩余不做消失的部分
     */
    cachePoolCardList
  }
}
/**
 * 计算卡片池中的位置
*/
export const computedPoolPosition = (card, hasRetainedPool) => {
  if (hasRetainedPool?.[card.position]?.isExistence) {
    card.height = CARD_SIZE.pool.height;
    card.width = CARD_SIZE.pool.width;
    card.top = getTopDeviation();
    card.left = LEFT_DEVIATION + (CARD_SIZE.pool.width + 7) * hasRetainedPool[card.position].index;
    card.isGameBox = false;
    /**
     * 如果已经在池中了，设置为true
     */
    card.isExistancePool = true;
    timeStemp.cardUpdateTime = new Date().getTime();
  }
  return card;
}
/**
 * 排序卡片池中剩余卡片
 */
export const poolSort = (cachePoolCardList) => {
  const hasSortPool = markPoolCard(cachePoolCardList)
  const hasRetainedPool = {};
  const sortCachPoolCardList: any[] = [];
  Object.keys(hasSortPool).sort((key1, key2) => hasSortPool[key2].count - hasSortPool[key1].count).forEach(key => {
    sortCachPoolCardList.push(...hasSortPool[key].list);
  })
  sortCachPoolCardList.forEach((card, index) => hasRetainedPool[card.position] = {isExistence: true, index});
  return [sortCachPoolCardList, hasRetainedPool, hasSortPool];
}

/**
 * 计算移除卡片
 */
export const computedRemoveCard = ({number = 3, heapList, poolList}) => {
  const positionTempPlan: CardItemType[] = [];
  const copyCardheapList = heapList || [];
  const copyCardPoolList = poolList || [];
  const ONE_RPX = getStaticState('oneRpx');
  const { screenHeight: SCREEN_HRIGHT, screenWidth: SCREEN_WIDTH, statusBarHeight, safeArea } = getStaticState('systemInfo');
  if (copyCardPoolList.length <= number) {
    positionTempPlan.push(...copyCardPoolList);
  } else {
    for(let i = 0; i < number ; i += 1) {
      const random = Math.floor(Math.random() * copyCardPoolList.length);
      const cardItem = copyCardPoolList[random];
      positionTempPlan.push(cardItem.position);
      copyCardPoolList.splice(random, 1);
    }
  }
  const positionTempLen = positionTempPlan.length;
  const initPosition = (SCREEN_WIDTH / ONE_RPX - (copyCardheapList[0].width + 5) * positionTempLen) / 2;
  let removeNumber = 0;
  const [sortPoolList, hasSortPool] = poolSort(copyCardPoolList);

  copyCardheapList.map(item => {
    const positionIdx = positionTempPlan.indexOf(item.position);
    if (positionIdx !== -1) {
      positionTempPlan.splice(positionIdx, 1);
      item.isDestruction = false;
      item.isExistancePool= false;
      item.isGameBox = true;
      item.top = (((SCREEN_HRIGHT - (statusBarHeight + safeArea.top)) / ONE_RPX - 280) + 10 + 3) - item.height - 50;
      item.left = initPosition + (item.width + 5) * removeNumber;
      removeNumber += 1;
    }
    return computedPoolPosition(item, hasSortPool);
  });
  return [copyCardheapList, sortPoolList];
}
  /**
   * 撤销一次数据
   */
export const revokeCard = (hook) => {
  const copyHook = copyJson(hook);
  const odlPoolList = copyHook.poolList.pop();
  const odlHeaplist = copyHook.heapList.pop();
  const oblLayerList = copyHook.layerList.pop();
  return {
    /**
     * 旧的卡片池数据
     */
    odlPoolList,
    /**
     * 旧的渲染列表数据
     */
    odlHeaplist,
    /**
     * 旧的层级树
     */
    oblLayerList,
    /**
     * 撤销后的数据缓存
     */
    copyHook
  }
}
/**
 * 是否消除中
 */
export const isBeingEliminated = (hasCount, eliminate) => {
  let flag = false
  Object.keys(hasCount).forEach((key) => {
    if (hasCount[key].count >= eliminate) {
      flag = true
      return
    }
  })
  return flag
}
/**
 * 是否游戏失败
 */
export const isGameFail = (sortCachPoolCardList, hasEnd = {}) => {
  let isGameFail = false;
  Object.keys(hasEnd).forEach(key => {
    if (hasEnd[key]?.count >= 3) {
      isGameFail = true;
    }
  });
  if(sortCachPoolCardList?.length >= 7 && !isGameFail) {
    return true
  }
  return false
}